<?php
	require_once('./src/classes/DBConnection.php');
	require('./src/config.php');
	require_once('./src/classes/LocalUser.php');
	
	header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT");
	header("Cache-Control: no-store, no-cache, must-revalidate");
	header("Cache-Control: post-check=0, pre-check=0", false);
	header("Pragma: no-cache");
	
	$connection = new DBConnection();
	$connection->connect($host, $username, $password, $dbname);
	
	if (! $connection->is_connected())
	{
		die($connection->get_error());
	}
	
	$curUser = new LocalUser($connection);
	$curUser->update_last_active($connection);
	
	if (! $curUser->isOnline)
	{
		die("You must be logged in to add a topic.");
	}
	
	$name =				$connection->clean_var($_GET['name']);
	$post = 			$connection->clean_var($_GET['post']);
	$forumid = 			$connection->clean_var($_GET['forumid']);
	$creatorid = 		$curUser->id;
	
	if ($name == "" || post == "")
		die("You must enter a name and a post to create the topic.");
	
	$query = "INSERT INTO topic SET 
				name='$name',
				forumid=$forumid,
				creatorid=$creatorid,
				creationdate=NOW()
	";
	
	if ($connection->query_noresult($query) == 0)
	{
		die($connection->get_error());
	}
	
	$row = $connection->get_result_array("SELECT id FROM topic ORDER BY creationdate DESC LIMIT 0, 1");
	
	if (empty($row))
		die($connection->get_error());
	
	$topicid = $row['id'];
	
	$query = "INSERT INTO post SET 
				topicid=$topicid,
				forumid=$forumid,
				posterid=$creatorid,
				creationdate=NOW(),
				body='$post'
	";
	
	if ($connection->query_noresult($query) == 0)
	{
		die($connection->get_error());
	}
	
	echo "Topic created successfully!";
	
	$connection->close();
?>